/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package server;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

// Hlavni trida pro daemona
public class Daemon extends Thread
{
	private static String _ip = "127.0.0.1";
	private static int _port = 2107;
	private static ServerSocket _socket;

	public Daemon()
	{
		setName("Daemon"); // Nastavi nazev vlakna
	}

	@Override
	public void run()
	{
		try
		{
			// Vytvori serverovy socket, ktery nasloucha na zvolenem portu a IP
			_socket = new ServerSocket(_port, 50, InetAddress.getByName(_ip));
		}
		catch (ConnectException e)
		{
			System.out.println("Daemon: Connecting error.");
			System.exit(-1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		try
		{
			while (true)
			{
				// Metoda accept ceka na pripojeni klienta a priradi mu vlastni vlakno
				// Tato metoda pozastavi chod vlakna dokud se nekdo nepripoji
				Socket s = _socket.accept();
				new DaemonClientThread(s).start();
				try
				{
					Thread.sleep(100);
				}
				catch (InterruptedException ee)
				{
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			shutdown();
		}
	}

	// Uzavreni socketu
	private static void shutdown()
	{
		try
		{
			_socket.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}
}
